package tsing.kc_work.cology.vipplatereceive;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import tsing.kc_work.cology.vipplatereceive.domain.EquityRecord;
import tsing.kc_work.cology.vipplatereceive.util.DesUtil;
import tsing.kc_work.cology.vipplatereceive.util.DesUtil2;
import org.springframework.util.StringUtils;
import tsing.javase.excption.BusinessException;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Date 14/6/2023 上午9:41
 *
 * 权益receive工程- 订购关系同步加解密工具类
 */
public class VipplateReceiveUtils {

    private static String testPrefixUrl = "http://172.16.60.28:8000/vipway/";
    /**
     * 解密
     */
    public static void  decryt(String str) throws BusinessException {
        String pwd = "lofmr3s6@#f23glp";
        if(StringUtils.hasLength(str)){

            JSONObject jsonObject = JSONObject.parseObject(str);

            String body = jsonObject.getString("body");
            try {
                String decode = DesUtil2.decode(body, pwd);
                System.out.println(decode);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


    /**
     * 订购关系同步加密
     */
    public static  void testSecretMethod(String channelId,String pwd,String productCode){
        String url = "http://127.0.0.1:8033/orderRelation/sycn2" ;
        // 渠道的秘钥配置在新平台的渠道表tb_vipplate_channel_indo 的 sign_secret

/*        String channelCode = "66";
        map.put("channelCode",channelCode);*/
        Map<String,Object> map = new HashMap<>();
        map.put("channelId",channelId);
        map.put("channelName","市场经营部");
        String tiamStamp = System.currentTimeMillis()+"";
        map.put("timestamp",tiamStamp);
        String sign = getSign(channelId,pwd,tiamStamp);
        map.put("sign",sign);
        String crytBody = getBody(pwd,productCode);
        map.put("body",crytBody);
        String data = JSON.toJSONString(map);
        System.out.println(HttpUtil.post(url, data));
//        System.out.println("解密--------------------------");

 /*       try {
            String deBody =DesUtil2.decode((String) map.get("body"),pwd);
            System.out.println("解密后的deBody：" + deBody);
            if(StringUtils.hasLength(deBody)){
                JSONArray array = JSONUtil.parseArray(deBody);
                List<OrderRelationDomain> list2 = JSONUtil.toList(array,OrderRelationDomain.class);
                System.out.println(JSON.toJSONString(list2));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }
    private static String getSign(String channelCode,String pwd,String timaStap) {
        String sign = SecureUtil.md5(channelCode +timaStap + pwd);
        return sign;
    }

    // l - [decryt,210] - 【领取receive服务】,【订购关系同步】,【订购原始数据校验】 ，订购关系解密后的数据：
    // [{"orderId":"LL-202402151857843064658","channel":"cap","loseEffectTime":"2029-12-31 23:59:59","userId":"18578430646","orderState":"0",
    // "productCode":"58","orderTime":"2024-02-15 20:15:45","province":"51",
    // "cancelOrderTime":"2029-12-31 23:59:59","effectTime":"2024-02-15 20:15:45"}]
    private static String getBody(String pwd ,String productCode) {
        String orderId = getOrder();
        int j = 9;
//        String userId = "155"+getRandom(7)+j;
        String userId = "15591895089";
        String result = "";
        List<Map> list = new ArrayList<>(10);
        for (int i = 0; i < 10; i++) {
            Map<String, String> map = new HashMap<>();
//            map.put("productCode","2023122818");
            map.put("productCode",productCode);
            map.put("province","51");
            map.put("orderId",getOrder());
//            map.put("orderId","LL-202402151857843064658");
            map.put("userId","155"+getRandom(7)+j);
//            map.put("userId","18578430646");
   /*         map.put("orderId",orderId);
            map.put("userId","15535264149");*/
            map.put("channel","cap");
            map.put("orderTime","2024-01-10 20:15:45");
            map.put("effectTime","2024-01-10 15:17:01");
            map.put("loseEffectTime","2029-12-31 23:59:59");
            map.put("cancelOrderTime","2024-02-10 15:17:01");
            map.put("orderState","0");
//            map.put("ruleId","1000003");
            list.add(map);
        }
        String str = JSON.toJSONString(list);
        System.out.println(str);

//        String str = "[{\"productCode\":\"20221212498\",\"orderTime\":\"2022-01-01 15:17:01\",\"province\":\"10\",\"orderId\":\"20221223135511589198616\",\"channel\":\"89861\",\"effectTime\":\"2022-01-01 15:17:01\",\"loseEffectTime\":\"2023-03-31 23:59:59\",\"userId\":\"13204809701\",\"orderState\":\"1\"}]";
        try {
            result = DesUtil2.encode(str,pwd);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public static String getOrder(){
        return format(new Date(), DatePattern.PURE_DATETIME_MS_PATTERN) +getRandom(6);
    }

    public static String getRandom(int length){

        Random random = new Random();
        String val = "";
        for (int i = 0; i < length; i++) {
            val += String.valueOf(random.nextInt(10));
        }
        return val;
    }
    /**
     *  Date 日期格式化
     * @param date
     * @param pattern
     * @return
     */
    public static String format(Date date, String pattern) {
        DateFormat format = null;
        try {
            format = new SimpleDateFormat(pattern);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            format = new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);
        }

        return format.format(date);
    }


    /**
     * 渠道领取接口
     * @param
     */
    public static void channelReceiveMethod(){

        try {
            channelCollectService();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    /**
     * 小程序领取接口
     */
    public static void appReceiveMethod(){

        procedureCollect();

    }


    public static void procedureCollect() {
        String url = "http://127.0.0.1:8033/procedureCollect" ;
        Map<String, String> map = new HashMap<String, String>();
        map.put("orderId", "202311022252566637371");
        map.put("productCode", "dqyceyw13");
        map.put("channelProductCode", "321300300001001");
        map.put("userId", "18673197465");
        map.put("account", "18673197465");
        map.put("accountType", "4"); //领取账号类型 1：QQ   4：手机号   5：其他账号
        map.put("orderTime", "2023-11-02 17:39:59");
        //map.put("channelRequestId", "202310121519230599321");
        //map.put("recordId", "5464"); // 领取失败重新领取需要传recordId
        String data = JSON.toJSON(map).toString();
        System.out.println(data);
        System.out.println("curl -X POST -i '" + url + "' --data '" + data+ "' -H 'Content-Type:application/json'");

    }



    public static void channelCollectService() throws Exception {
        String url = "http://127.0.0.1:8033/channel/collect/v1";

/*        String channelId = "117d273ad1d24cd881cd8ca22f5b3f4b";// 流量32
        String secrete = "KIH7654HY876K89Gt5432DFg3456Vb87";// 流量32*/
        String channelId="b331e900e8a94b60a28769594ef5b185";// 流量测试
        String secrete = "Mkqaxz4FjlHKzfqozajNWxS2Gtjb7wwR";//流量测试
/*        String channelId="3b3ca3c5329f4fb8a84247741ec77053";// 流量S1M1 测试
        String secrete = "Mkqaxz4FjlHKzfqozajNWxS2Gtjb7wwR";//流量S1M1 测试*/
//        channelId = "117d273ad1d24cd881cd8ca22f5b3f4b"; // 正式
        String channelName = "流量";
//        channelName = "联通沃音乐文化有限公司";
        String timestamp =  System.currentTimeMillis()+"";
//        String secrete = "bf9599de344d9265e4744601ae824487878c6795";//从tb_vipplate_channel_info根据channelId查sign_secret

//        secrete="KIH7654HY876K89Gt5432DFg3456Vb87"; // 正式
        String sign = SecureUtil.md5(channelId + timestamp + secrete);
        String orderTime =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) ;
        //orderTime="2023-08-22 23:59:59";
        Map<String, String> map = new HashMap<String, String>();
        // 月包
/*        map.put("orderId", "LL-202311221320794833159");
        map.put("productCode", "998856");*/

        // 次包
        map.put("orderId", "0aa14776893e4a24b9f27aeca0d354d1");
        map.put("productCode", "9010");
        map.put("channelProductCode", "661300500010004");
//        map.put("interestsCode", "2300300001");
        map.put("groupId", "");
        map.put("userId",  "13016255670");
        map.put("account", "13016255670");
        map.put("accountType", "4");
        map.put("orderTime", orderTime);
        map.put("channelRequestId", "");
//        map.put("ruleId", "1000188");
//        map.put("ruleId", "1000249");
//        map.put("ruleId", "1000188");

        String body = JSON.toJSONString(map);
        System.out.println("body>>>"+body);
        body = DesUtil.encode(body, secrete);
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("channelId", channelId);
        paramMap.put("channelName", channelName);
        paramMap.put("sign", sign);
        paramMap.put("timestamp", timestamp);
        paramMap.put("body", body);
        String data = JSON.toJSONString(paramMap);
        System.out.println("curl -H 'Content-Type:application/json' -X POST -i  '"+ url + "'  --data '" + data + "' -vv");
//        System.out.println("curl -X POST -i '" + url + "' --data '" + data+ "' -H 'Content-Type:application/json'");
//        System.out.println(HttpUtil.post(url, data));

    }


    /**
     * 调直冲接口
     * @param
     * @return
     * @throws Exception
     */
    public static String unifygivevip()  {
        String url = "http://localhost:8020/unifygivevip";

        EquityRecord equityRecord = EquityRecord.builder()
                .channelProductCode("1")
                .channelCode("241")
                .accountNumber("15173343158")
                .phoneNumber("15173343158")
                .firstTimestamp(null)
                .productCode("1100303532")
                .accountType("4")
                .orderId(getOrder())
                .channelProductCode("245555500001001")
                .build();


        final HashMap<String, Object> map = new HashMap<>();
        String requestId = equityRecord.getOrderId();
        String timestamp = System.currentTimeMillis() + "";
        String channelCode = equityRecord.getChannelCode(); // tb_vipplate_channel_info.code todo
        String interest = equityRecord.getChannelProductCode();
        String userAccount = equityRecord.getAccountNumber();
        String userid = equityRecord.getPhoneNumber();
        String tradeId = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
        ArrayList<Map<String, Object>> timeStampList = new ArrayList<>();
        if (equityRecord.getFirstTimestamp() != null && !equityRecord.getFirstTimestamp().isEmpty()) {
            //使用第一次的订单
            String[] timestampList = equityRecord.getFirstTimestamp().split(",");
            Map<String, Object> hmap = new HashMap<>();
            hmap.put("timestamp", timestampList[0]);
            hmap.put("orderType", "0"); // 0 原始订单、1 重试订单
            timeStampList.add(hmap);
            if (timestampList.length > 1) {
                hmap = new HashMap<>();
                hmap.put("timestamp", timestampList[1]);
                hmap.put("orderType", "1"); // 0 原始订单、1 重试订单
                timeStampList.add(hmap);
            }
            hmap = new HashMap<>();
            hmap.put("timestamp", timestamp);
            hmap.put("orderType", "1"); // 0 原始订单、1 重试订单
            timeStampList.add(hmap);
            equityRecord.setFirstTimestamp(timestampList[0] + "," + timestamp);
        } else {
            Map<String, Object> hmap = new HashMap<>();
            hmap.put("timestamp", timestamp);
            hmap.put("orderType", "0"); // 0 原始订单、1 重试订单
            equityRecord.setFirstTimestamp(timestamp);
            timeStampList.add(hmap);
        }
        map.put("requestId", requestId);
        map.put("timeStampList", timeStampList);
        map.put("operateType", "1"); //0：直充 1:领取 2:续送
        map.put("channelCode", channelCode);
        map.put("interest", interest);
        map.put("userAccount", userAccount);
        //岁末年初参数
        map.put("businessProductCode", equityRecord.getProductCode());
        map.put("activityId", "");
        map.put("userId", userid);
        map.put("tradeId", tradeId);
        map.put("accountType",equityRecord.getAccountType());
//        JSONObject data = JSON.parseObject(JSON.toJSONString(map));
        return HttpUtil.post(url,JSON.toJSONString(map));
//        return JSON.parseObject(JSON.toJSONString(map));
    }





    public static void main(String[] args) {





        //生成订购关系同步
        String pwd = "Mkqaxz4FjlHKzfqozajNWxS2Gtjb7wwR"; // 测试流量
        String channelId = "b331e900e8a94b60a28769594ef5b185"; // 老测试流量
        String productCode = "999999"; // 月包
//        String productCode = "9021"; // 次包

//        String pwd = "bf9599de344d9265e4744601ae824487878c6795"; // 沃音乐
//        String pwd = "bd251fc33c5f9a27801310ff0415448e76b00d52"; // 沃音乐


//        String channelId = "a0deb59ce6c9425591af327c6d4bf87d"; // 沃音乐
//        String channelId = "2c7b50e1585148cf9a58522ad54ba85a"; // 市场经营部

        // 批量
//        testSecretMethod(channelId,pwd,productCode);

/*
        for (int i = 0; i < 10; i++) {
            testSecretMethod(channelId,pwd,productCode);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
*/



        // 渠道领取
//        channelReceiveMethod();


        // 小程序领取
//        appReceiveMethod();


        // 调giveVip
/*        System.out.println(unifygivevip());


//        String url = "localhost:8020/poolUnifyGiveVip";
        String url = "http://172.16.60.28:8000/vipway/givevip/poolUnifyGiveVip";
        String tradeId = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
        ArrayList<Map<String, Object>> timeStampList = new ArrayList<>();
        Map<String, Object> hmap = new HashMap<>();
        hmap.put("timestamp", System.currentTimeMillis() + "");
        hmap.put("orderType", "0"); // 0 原始订单、1 重试订单
        timeStampList.add(hmap);

        HashMap<String,Object> map = new HashMap<>();
        map.put("requestId", IdUtil.simpleUUID());
        map.put("timeStampList", timeStampList);
        map.put("operateType", "1"); //0：直充 1:领取 2:续送
        map.put("channelCode", "32"); // 测试渠道
        map.put("userAccount", "15173343158");
        map.put("orderType", "0"); // 0 原始订单、1 重试订单
        map.put("userId", "15173343158");
        map.put("interest", "9999999"); // 对应渠道产品编码
        map.put("interestsCode","5555500002");
        map.put("vippoolCode","20375555500002001");
        map.put("businessProductCode", null);
        map.put("tradeId", tradeId);
        map.put("accountType","4");//1.QQ号 ，2微信号, 3微信openid,4手机号,6QQopenid
        map.put("activityId", "");
        map.put("claimRuleId","");
        map.put("supplierPrice","18.0"); // 我方采购单价
        map.put("supplierPriceNotax","20.5");
        map.put("orderPriceTaxIncluded",0);// 我方供货单价
        map.put("orderPriceTaxExclusive",0);


        String data = JSON.toJSONString(map);
        System.out.println("curl -X POST -i '" + url + "' --data '" + data+ "' -H 'Content-Type:application/json'");*/


//        System.out.println(HttpUtil.post(url, JSON.toJSONString(map)));


        Integer i = 2;
        if(i!= Integer.parseInt("2")){
            System.out.println("不相同");

        }else{
            System.out.println("相同");

        }

        /**
         * 查询权益通道相关参数SQL:
         *       SELECT
         *             a.related_id ywid,
         *             a.interests_id  interestsId,
         *             b.interests_cont interestsCont ,
         *             b.interests_code equitySkuCode ,
         *             a.vippool_cont vippoolCont,
         *             a.vippool_type vippoolType,
         *             a.recharge_type rechargeType,
         *             a.input_num inputNum,
         *             a.supplier_price supplierPrice,
         *             a.supplier_price_notax  supplierPriceNotax,
         *             a.vippool_code vippoolCode,
         *             a.product_code productCode
         *         FROM
         *             tb_vipplate_interests_pool a
         *         LEFT JOIN tb_vipplate_interests b ON a.interests_id = b.id
         *         WHERE
         *             a.del = '1'
         *             and a.vippool_code  = #{vippoolCode}
         */

        String account = "充值账号";
        String userId = "手机号";
        String vippoolCode = "权益通道编码";
        String accountType = "4";//1.QQ号 ，2微信号, 3微信openid,4手机号,6QQopenid
        String equitySkuCode = "权益编码";
        String supplierPrice = "采购价";
        String supplierPriceNotax = "采购价不含税";
        // 只需要修改上面6个参数值

        String requestId = IdUtil.simpleUUID();// uuid
        String tradeId = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
        ArrayList<Map<String, Object>> timeStampList = new ArrayList<>();
        Map<String, Object> hmap = new HashMap<>();
        hmap.put("timestamp", System.currentTimeMillis() + "");
        hmap.put("orderType", "0"); // 0 原始订单、1 重试订单
        timeStampList.add(hmap);

        HashMap<String,Object> map = new HashMap<>();
        map.put("requestId", requestId);
        map.put("timeStampList", timeStampList);
        map.put("operateType", "1"); //0：直充 1:领取 2:续送
        map.put("channelCode", "32"); // 测试渠道
        map.put("userAccount", account);
        map.put("orderType", "0"); // 0 原始订单、1 重试订单
        map.put("userId", userId);
        map.put("interest", "9999999"); // 对应渠道产品编码
        map.put("interestsCode",equitySkuCode);
        map.put("vippoolCode",vippoolCode);
        map.put("businessProductCode", null);
        map.put("tradeId", tradeId);
        map.put("accountType",accountType);//1.QQ号 ，2微信号, 3微信openid,4手机号,6QQopenid
        map.put("activityId", "");
        map.put("claimRuleId","");
        map.put("supplierPrice",supplierPrice); // 我方采购单价
        map.put("supplierPriceNotax",supplierPriceNotax);
        map.put("orderPriceTaxIncluded",0);// 我方供货单价
        map.put("orderPriceTaxExclusive",0);

        String param = JSON.toJSONString(map);

        String url = "http://100.0.13.108:8000/vipway/givevip/poolUnifyGiveVip";
        // 生成调接口的命令
        System.out.println("curl -X POST -i '" + url + "' --data '" + param+ "' -H 'Content-Type:application/json'");


    }


}
